﻿using SQLite.CodeFirst;
using System.Data.SQLite;
using System.Data.Entity;
using System.Data.Entity.Core.Common;
using System.Data.SQLite.EF6;
using System.IO;
using System.Windows.Forms;

namespace LeakView.database
{
    class Sqlites : DbConfiguration
    {
        /// <summary>
        /// SQLite数据库连接
        /// </summary>
        /// <returns></returns>
        public static SQLiteConnection GetConnection()
        {

            return new SQLiteConnection()
            {
                ConnectionString = new SQLiteConnectionStringBuilder()
                {
                    DataSource = Path.Combine(Application.StartupPath, "db/sqlite.db"),
                    ForeignKeys = true
                }.ConnectionString
            };

        }

        /// <summary>
        /// SQLite数据库配置
        /// </summary>
        public Sqlites()
        {
            SetProviderFactory("System.Data.SQLite", SQLiteFactory.Instance);
            SetProviderFactory("System.Data.SQLite.EF6", SQLiteProviderFactory.Instance);
            SetProviderServices("System.Data.SQLite", (DbProviderServices)SQLiteProviderFactory.Instance.GetService(typeof(DbProviderServices)));
        }

    }


    /// <summary>
    /// SQLite数据库DbContext
    /// </summary>
    class SqliteDbContext : DbContext
    {
        public virtual DbSet<NetworkAlarmEntry> NetworkAlarmMaster { get; set; }

        public virtual DbSet<MiscAlarmEntry> MiscAlarmMaster { get; set; }

        //public virtual DbSet<LogEntry> LogMaster { get; set; }


        public SqliteDbContext() : base(Sqlites.GetConnection(), true)
        {

        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {

            modelBuilder.Entity<NetworkAlarmEntry>().ToTable("NetworkAlarmMaster").HasKey(p => p.ID);
            modelBuilder.Entity<MiscAlarmEntry>().ToTable("MiscAlarmMaster").HasKey(p => p.ID);

            var initializer = new SqliteDropCreateDatabaseWhenModelChanges<SqliteDbContext>(modelBuilder);
            //var initializer = new SqliteCreateDatabaseIfNotExists<SqliteDbContext>(modelBuilder);

            Database.SetInitializer(initializer);

        }

    }
}
